package com.rz.paas.test.inChannel

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.get
import androidx.core.view.size
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.tabs.TabLayoutMediator
import com.rz.paas.test.R
import com.rz.paas.test.inChannel.adapter.*
import com.rz.paas.test.inChannel.viewModel.CommunicationMode
import com.rz.paas.test.inChannel.viewModel.CommunicationViewModel
import kotlinx.android.synthetic.main.fragment_communication.*
import kotlinx.android.synthetic.main.layout_communication_bottom_menu.*
import kotlin.random.Random


class CommunicationFragment : Fragment() {

    private val communicationViewModel by activityViewModels<CommunicationViewModel>()

    private val videoAdapter by lazy {
        VideoListAdapter(requireContext())
    }

    val mBottomSheetBehavior by lazy {
        BottomSheetBehavior.from(communication_bottom_menu);
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_communication, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        video_rv.layoutManager = GridLayoutManager(context, 2)
        video_rv.itemAnimator = null
        video_rv.adapter = videoAdapter
        val direction = VideoToppingDirection(requireContext())
        video_rv.addItemDecoration(direction)

        val listData = mutableListOf<VideoData>()
        initData(listData)
        videoAdapter.data = listData

        videoAdapter.addObserver(observer)

        main_view.setNotifyItem(object : Notify {
            override fun notifyChange(position: Int) {
                main_view_container.visibility = View.INVISIBLE
                videoAdapter.data[position].isTopping = false
                videoAdapter.notifyItemChanged(position)
            }
        })

        shrink_click.setOnClickListener {
            main_view.hideSelf()

        }
        initBottomView()

        showViewByModel()

    }

    private fun initBottomView() {
        val peekHeight = resources.displayMetrics.heightPixels
        val coordinatorLayout =
            communication_bottom_menu.layoutParams as CoordinatorLayout.LayoutParams
        coordinatorLayout.height = peekHeight - peekHeight / 6
        communication_bottom_menu.layoutParams = coordinatorLayout

        communication_bottom_menu.setOnClickListener {
            if (mBottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED)
                mBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
            else if (mBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) {
                mBottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
            }
        }

        exit_button.setOnClickListener {
            exitCommunication()
        }

        view_pager.adapter = PagerAdapter(this)

        TabLayoutMediator(tab_layout, view_pager) { tab, position ->
            val inflate = View.inflate(context, R.layout.layout_tab_custom, null)
            tab.customView = inflate
            inflate.findViewById<TextView>(R.id.tab_layout_title)?.setText(getTabTitle(position))
            inflate.findViewById<ImageView>(R.id.tab_layout_image)
                ?.setImageResource(getTabIcon(position))
        }.attach()
    }

    private fun exitCommunication() {
        communicationViewModel.finishActivity()
    }

    fun showViewByModel() {
        if (communicationViewModel.getCommunicationMode() == CommunicationMode.LIVE_MODE_AUDIENCE) {
            video_rv.visibility = View.INVISIBLE
            not_have_anchor.visibility = View.VISIBLE
        } else {
            not_have_anchor.visibility = View.INVISIBLE
            video_rv.visibility = View.VISIBLE
        }

    }

    private fun getTabIcon(position: Int): Int {
        return when (position) {
            CHANNEL_SETTING_INDEX -> R.drawable.icon_channel_setting
            STREAMING_SETTING_INDEX -> R.drawable.icon_streaming_setting
            USER_INFORMATION_INDEX -> R.drawable.icon_user_information
            PROCESS_DATA_INDEX -> R.drawable.icon_process_data
            else -> throw IndexOutOfBoundsException()
        }
    }

    private fun getTabTitle(position: Int): String? {
        return when (position) {
            CHANNEL_SETTING_INDEX -> getString(R.string.channel_setting)
            STREAMING_SETTING_INDEX -> getString(R.string.streaming_setting)
            USER_INFORMATION_INDEX -> getString(R.string.user_information)
            PROCESS_DATA_INDEX -> getString(R.string.process_data)

            else -> null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        videoAdapter.deleteObservers()
    }

    val imageRes = intArrayOf(
        R.mipmap.icon_test_image_01,
        R.mipmap.icon_test_image_02,
        R.mipmap.icon_test_image_03,
        R.mipmap.icon_test_image_04,
        R.mipmap.icon_test_image_05,
        R.mipmap.icon_test_image_06,
        R.mipmap.icon_test_image_07,
        R.mipmap.icon_test_image_08,
        R.mipmap.icon_test_image_09,
    )

    private fun initData(listData: MutableList<VideoData>) {
        for (index in 0..30) {

            var videoData = VideoData()
            videoData.imageRes = imageRes[index % imageRes.size]
            videoData.userId = (index).toString()
            videoData.deviceName = if (index % 2 == 0) "front" else "back"
            videoData.doubleStream = index % 5 == 0
            videoData.camera_operator_iv = generateImageView(R.mipmap.camera_close_icon)
            videoData.mic_operator_iv = generateImageView(R.mipmap.mic_open_icon)
            videoData.switch_camera_iv = generateImageView(R.mipmap.switch_camera_icon)
            videoData.topping_operator_iv = generateImageView(R.mipmap.topping_close_icon)
            videoData.hd_operator_iv = generateImageView(R.mipmap.hd_open_icon)
            if (index % (Random.nextInt(5)+1) == 0) {
                videoData.closeCamera = true
            }
            if (index == 1) {
                videoData.userId = (index - 1).toString()
            }
            videoData.isSelf = index in 0..1
            listData.add(videoData)
        }
    }

    private fun generateImageView(res: Int): ImageView {
        var imageView = ImageView(context)
        imageView.setImageResource(res)
        imageView.setBackgroundResource(R.drawable.video_view_icon_bg)
        return imageView
    }

    private val TAG = "CommunicationFragment"
    private val observer = object : Observer {
        override fun update(position: Int, itemView: View) {
            val frameLayout = (itemView as ViewGroup)[0] as FrameLayout
            val videoData = videoAdapter.data[position]
            Log.d(
                TAG,
                "itemPosition: ${videoData.userId}_${videoData.deviceName} position:${position} video_rv:${video_rv.size} "
            )
            if (frameLayout.childCount > 0) {
                if (main_view_container.visibility != View.VISIBLE)
                    main_view_container.visibility = View.VISIBLE

                main_view.onActive(frameLayout[0], videoData, position)
                iconTips(videoData, position)
            }

        }

    }

    private fun iconTips(videoData: VideoData, position: Int) {

        if (!videoData.isSelf) {
            hd_operator_iv.visibility = View.VISIBLE
            topping_operator_iv.visibility = View.GONE
            switch_camera_iv.visibility = View.GONE
        } else {
            hd_operator_iv.visibility = View.GONE
            topping_operator_iv.visibility = View.VISIBLE
            switch_camera_iv.visibility = View.VISIBLE
        }

        getCameraIcon(camera_operator_iv, videoData)
        camera_operator_iv.visibility = View.VISIBLE
        camera_operator_iv.setOnClickListener {
            videoData.muteCamera = !videoData.muteCamera
//            videoAdapter.setData(position, videoData)
            videoAdapter.getCameraIcon(videoData.camera_operator_iv!!, videoData)
            videoAdapter.findSameUserIdData(position, videoData)
            getCameraIcon(camera_operator_iv, videoData)
        }

        getMicIcon(mic_operator_iv, videoData)
        mic_operator_iv.visibility = View.VISIBLE
        mic_operator_iv.setOnClickListener {
            videoData.muteMicrophone = !videoData.muteMicrophone
//            videoAdapter.setData(position, videoData)
            videoAdapter.getMicIcon(mic_operator_iv, videoData)
            videoAdapter.findSameUserIdData(position, videoData)
            getMicIcon(mic_operator_iv, videoData)
        }

    }

    private fun getCameraIcon(iv: ImageView, videoData: VideoData): View {
        iv.alpha = 1f
        if (videoData.closeCamera && videoData.muteCamera) {
            iv.setImageResource(R.mipmap.icon_close_camera)
            iv.alpha = 0.5f
        } else if (videoData.closeCamera) {
            iv.setImageResource(R.mipmap.icon_close_camera)
        } else if (videoData.muteCamera) {
            iv.setImageResource(R.mipmap.icon_mute_camera)
        } else {
            iv.setImageResource(R.mipmap.camera_close_icon)
        }
        return iv
    }

    private fun getMicIcon(iv: ImageView, videoData: VideoData): View {
        iv.alpha = 1f
        if (videoData.closeMicrophone && videoData.muteMicrophone) {
            iv.setImageResource(R.mipmap.icon_close_microphone)
            iv.alpha = 0.5f
        } else if (videoData.closeMicrophone) {
            iv.setImageResource(R.mipmap.icon_close_microphone)
        } else if (videoData.muteMicrophone) {
            iv.setImageResource(R.mipmap.icon_mute_microphone)
        } else {
            iv.setImageResource(R.mipmap.mic_open_icon)
        }
        return iv
    }
}